
/* Возможные состояния регулятора напряжения
*  
*  0 - 1-27v (ручное регулирование)
*  1 - 3.3v
*  2 - 5v
*  3 - 9v
*  4 - 12v
*  5 - 15v
*  6 - 24v
*
*/

#define regPinSwitch 0
#define regPin3_3 1
#define regPin5 2
#define regPin9 3
#define regPin12 4
#define regPin15 5
#define regPin24 6
#define regPinManual 7



int reg_curPin = 1;
int reg_curVoltage = 0;
int reg_curState = false;

void regulator_init() {
  pinMode(regPinSwitch,OUTPUT);   //Пин выключателя
  pinMode(regPin3_3,OUTPUT);      //Пин 3.3v
  pinMode(regPin5,OUTPUT);        //Пин 5v
  pinMode(regPin9,OUTPUT);        //Пин 9v
  pinMode(regPin12,OUTPUT);       //Пин 12v
  pinMode(regPin15,OUTPUT);       //Пин 15v
  pinMode(regPin24,OUTPUT);       //Пин 24v
  pinMode(regPinManual,OUTPUT);   //Пин ручное управление

  byte volts = EEPROM.read(1);
  byte state = EEPROM.read(2);
  byte restore = EEPROM.read(3);

  if(volts > 10) volts=v3_3;
  if(state > 10) volts=0;
  if(restore > 10) restore=0;
  
  if(state == 1 and restore == 1)
    regulator_on();
  else
    regulator_off();

  regulator_set(volts);
}

void regulator_set(int state) {
  bool isPower = reg_curState;
  regulator_off();
  digitalWrite(reg_curPin,LOW);
  
  if(state == v3_3) {
    digitalWrite(regPin3_3,HIGH);
    reg_curPin = regPin3_3;
    reg_curVoltage = state;
  }
  else if(state == v5) {
    digitalWrite(regPin5,HIGH);
    reg_curPin = regPin5;
    reg_curVoltage = state;
  }
  else if(state == v9) {
    digitalWrite(regPin9,HIGH);
    reg_curPin = regPin9;
    reg_curVoltage = state;
  }
  else if(state == v12) {
    digitalWrite(regPin12,HIGH);
    reg_curPin = regPin12;
    reg_curVoltage = state;
  }
  else if(state == v15) {
    digitalWrite(regPin15,HIGH);
    reg_curPin = regPin15;
    reg_curVoltage = state;
  }
  else if(state == v24) {
    digitalWrite(regPin24,HIGH);
    reg_curPin = regPin24;
    reg_curVoltage = state;
  }
  else if(state == manual) {
    digitalWrite(regPinManual,HIGH);
    reg_curPin = regPinManual;
    reg_curVoltage = state;
  }
  if(isPower) regulator_on();
  EEPROM.write(1, state);
}

void regulator_off(){
  digitalWrite(regPinSwitch,LOW);
  reg_curState = false;
  EEPROM.write(2, 0);
}

void regulator_on(){
  digitalWrite(regPinSwitch,HIGH);
  reg_curState = true;
  EEPROM.write(2, 1);
}

void regulator_toggle(){
  digitalWrite(regPinSwitch,!reg_curState);
  reg_curState = !reg_curState;

  if(reg_curState)
    EEPROM.write(2, 1);
  else
    EEPROM.write(2, 0);
}

int regulator_getVoltage(){
  return reg_curVoltage;
}

bool regulator_getState(){
  return reg_curState;
}

bool regulator_isRestore(){
  byte restore = EEPROM.read(3);
  if(restore == 1) return true;
  return false;
}

void regulator_restoreSet(int restore){
  EEPROM.write(3, restore);
}


